#include "drawlabel.h"

extern QString tmpDir;

DrawLabel::DrawLabel(QWidget *parent) : QLabel(parent)
{
    //this->setStyleSheet(QString::fromUtf8("border:3px solid blue"));
    installEventFilter(this);
    update();
    this->penSize = 2;
}

void DrawLabel::setPenColor(QColor color)
{
    penColor = color;
}
void DrawLabel::setBrushColor(QColor color)
{
    brushColor = color;
}
void DrawLabel::setBackColor(QColor color)
{
    qDebug() << "setback";
    backColor = color;
    QString back = "background-color:rgb(%1)";
    this->setStyleSheet(back.arg(QString("%1,%2,%3").arg(backColor.red()).arg(backColor.green()).arg(backColor.blue())));
    if(!pixmap.isNull())
    {
        //pixmap.fill(backColor);
    }
    QDir folder(tmpDir);
    if (!folder.exists())
    {
        return;
    }

    QStringList files = folder.entryList(QDir::Files);
    for (const QString& file : files)
    {
        QString filePath = folder.filePath(file);
        QFile::remove(filePath);
    }

    drawType = -1;
    update();
}
void DrawLabel::setPenSize(int size)
{
    this->penSize = size;
    qDebug() << "set pen : " << this->penSize;
}
void DrawLabel::setDrawType(int type)
{
    drawType = type;
    qDebug()<< "drawtype " << drawType;
    if(drawType== DRAW_BACK)
    {
        if(tmpIdx>0)
        {
            tmpIdx--;
            backCnt++;
            update();
        }
    }
    else if(drawType == DRAW_SAVE)
    {
        saveTmp();
    }
    else if(drawType == DRAW_CLEAR)
    {
        tmpIdx = 0;
        QDir folder(tmpDir);
        if (!folder.exists())
        {
            return;
        }

        QStringList files = folder.entryList(QDir::Files);
        for (const QString& file : files)
        {
            QString filePath = folder.filePath(file);
            QFile::remove(filePath);
            qDebug() << "remove";
        }
        tmpIdx = 0;
        update();
    }
  //  pixmap = this->grab();
  //  pixmap.save(tmpDir + "tmp_" + QString::number(tmpIdx) + ".png");
    //tmpIdx++;

}
void DrawLabel::setPolygonType(int type)
{
    polygonType = type;
}

void DrawLabel::setAutoFill(int a)
{
    autoFill = a;
}

bool DrawLabel::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        // 左键单击
        if(mouseEvent->button() == Qt::LeftButton)
        {
            //qDebug() << mouseEvent->pos();
            //            startX = mouseEvent->pos().x();
            //            startY = mouseEvent->pos().y();
            //            endX = startX+100;
            //            endY = startY+100;
            //            update();
        }
        else
        {
            return false;
        }
    }
    return QObject::eventFilter(obj, event);
}

void DrawLabel::leaveEvent(QEvent *e)
{
    //drawType = -1;
}
void DrawLabel::focusOutEvent(QFocusEvent *event)
{

}

void DrawLabel::paintEvent(QPaintEvent *)
{
    QPainter p;
    // 打开历史数据
    pixmap = QPixmap(tmpDir + "tmp_" + QString::number(tmpIdx-1) + ".png");
    // 如果为空，则设置为控件大小
    if(pixmap.isNull())
    {
        pixmap = QPixmap(this->width(), this->height());
        pixmap.fill(backColor);
    }
    // 在map上绘图
    // 图片缩放到控件大小
    pixmap= pixmap.scaled(width(),height(),Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    // begin有返回值，设置正常返回为true
    p.begin(&pixmap);
    // 设置画笔
    QPen pen;
    pen.setColor(penColor);
    pen.setWidth(penSize);
    p.setPen(pen);
    // 设置画刷
    QBrush brush;
    brush.setColor(brushColor);
    brush.setStyle(Qt::SolidPattern);
    if(autoFill)
        p.setBrush(brush);
    else
        p.setBrush(Qt::NoBrush);
    // 开始绘画
    if(drawType == DRAW_LINE)
    {
        p.drawLine(startX, startY, endX, endY);
    }
    else if(drawType == DRAW_RECT)
    {
        if(endX>startX && endY>startY)
            p.drawRect(startX, startY, abs(endX-startX), abs(endY-startY));
        else if(endX>startX && endY<startY)
            p.drawRect(startX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY<startY)
            p.drawRect(endX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY>startY)
            p.drawRect(endX, startY, abs(endX-startX), abs(endY-startY));
    }
    else if(drawType == DRAW_ARECT)
    {
        if(endX>startX && endY>startY)
            p.drawRoundRect(startX, startY, abs(endX-startX), abs(endY-startY));
        else if(endX>startX && endY<startY)
            p.drawRoundRect(startX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY<startY)
            p.drawRoundRect(endX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY>startY)
            p.drawRoundRect(endX, startY, abs(endX-startX), abs(endY-startY));
    }
    else if(drawType == DRAW_ELLIPSE)
    {
        if(endX>startX && endY>startY)
            p.drawEllipse(startX, startY, abs(endX-startX), abs(endY-startY));
        else if(endX>startX && endY<startY)
            p.drawEllipse(startX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY<startY)
            p.drawEllipse(endX, endY, abs(endX-startX), abs(endY-startY));
        else if(endX<startX && endY>startY)
            p.drawEllipse(endX, startY, abs(endX-startX), abs(endY-startY));
    }
    else if(drawType == DRAW_ARC)
    {
        if(cubicPoints.size()>=2)
        {
            qDebug() << cubicPoints.size();
            QList<QPoint> ps;
            ps << QPoint(startX, startY) <<QPoint(endX,endY);
            QPainterPath path(ps[0]);
            for (int i = 0; i < ps.size() - 1; ++i) {
                // 控制点的 x 坐标为 sp 与 ep 的 x 坐标和的一半
                // 第一个控制点 c1 的 y 坐标为起始点 sp 的 y 坐标
                // 第二个控制点 c2 的 y 坐标为结束点 ep 的 y 坐标
                QPointF sp = ps[i];
                QPointF ep = ps[i+1];
                QPointF c1 = QPointF((sp.x() + ep.x()) / 2, sp.y());
                QPointF c2 = QPointF((sp.x() + ep.x()) / 2, ep.y());
                //        QPointF c2 = QPointF(ep.x(), (sp.y() + ep.y()) / 2);
                path.cubicTo(c1, c2, ep);
            }
            p.drawPath(path);
        }
    }
    else if(drawType == DRAW_POLYGON)
    {
        p.drawPoint(startX, startY);
        qDebug() << "poly:" << polygonType << ":" <<polyPoints.size();
        if(polyPoints.size() == polygonType)
        {
            p.drawPolygon(polyPoints);
            polyPoints.resize(0);
        }
    }
    else if(drawType == DRAW_PEN)
    {
        p.drawPolyline(QPolygon(points));
    }
    else if(drawType == DRAW_ERASE)
    {
        p.save();
        // 设置画笔
        QPen pen;
        pen.setColor(backColor);
        pen.setWidth(15);
        p.setPen(pen);
        p.drawLine(startX, startY, endX, endY);
        p.restore();
    }

    // 停止绘制
    p.end();
    // 绘制map，这样才能显示出来
    QPainter p1(this);
    p1.setRenderHint(QPainter::Antialiasing);
    p1.setRenderHint(QPainter::TextAntialiasing);
    //p1.translate((1-scaleFactor)*width()/2, (1-scaleFactor)*width()/2);
    // 缩放图片
    pixmap= pixmap.scaled(width()*scaleFactor,height()*scaleFactor,Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    p1.drawPixmap(0, 0,pixmap);

}

void DrawLabel::mouseMoveEvent(QMouseEvent *event)
{
    endX = event->pos().x();
    endY = event->pos().y();
    // 自由曲线点
    if(drawType==DRAW_PEN)
    {
        points.push_back(event->pos());
    }
    else if(drawType == DRAW_ARC)
    {
        cubicPoints.push_back(event->pos());
    }
    else if(drawType == DRAW_ERASE)
    {
        // 擦除要时刻保存历史
        pixmap.save(tmpDir + "tmp_" + QString::number(tmpIdx) + ".png");
        tmpIdx++;
    }
    update();
}

void DrawLabel::mousePressEvent(QMouseEvent *event)
{
    // 初始化数据
    startX = event->pos().x();
    startY = event->pos().y();
    endX = startX;
    endY = startY;
}

void DrawLabel::mouseReleaseEvent(QMouseEvent *event)
{
    if(drawType==DRAW_ARC || drawType==DRAW_LINE || drawType==DRAW_RECT || drawType==DRAW_ARECT || \
            drawType==DRAW_ELLIPSE || drawType==DRAW_PEN || drawType==DRAW_POLYGON || drawType==DRAW_ERASE)
    {
        // 多边形点
        if(drawType == DRAW_POLYGON)
        {
            polyPoints.append(event->pos());
            update();
        }
        // 松开鼠标后，保存当前绘制
        // 截屏
        pixmap = this->grab();
        // 保存
        pixmap.save(tmpDir + "tmp_" + QString::number(tmpIdx) + ".png");
        tmpIdx++;
        // 重置缩放参数
        scaleFactor = 1;
    }
    // 清空数据
    points.clear();
    cubicPoints.clear();
    startX = 0;
    startY = 0;
    endX = 0;
    endY = 0;
}

// 滚轮缩放
void DrawLabel::wheelEvent(QWheelEvent *event)
{
    const double delta = event->angleDelta().y() / 8;
    scaleFactor += delta * 0.001;
    double mins = 0.1;
    double maxs = 5;
    scaleFactor = qBound(mins, scaleFactor, maxs); // Limit the scale factor between 0.5 and 2.0
    // 更新绘图
    update();
}

// 保存图片
void DrawLabel::saveTmp()
{
    qDebug() << "save file";
    QString filePath = QFileDialog::getSaveFileName(this, "Save File", "", "pix files (*.jpeg *.png *.jpg)");
    if(!filePath.isNull())
        pixmap.save(filePath);
}

QFile DrawLabel::restoreTmp()
{

}
